#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "database.h"
#include "login.h"
#define MAX_STRING_LENGTH 128

#define RESPOND(client, code, message) fprintf(client, "%d %s\r\n", code, message)

typedef struct USER_MESSAGE
{
	char username[MAX_STRING_LENGTH];
	char password[MAX_STRING_LENGTH];
	int is_vaild_user;
}USER_MESSAGE;


void login_handler(FILE *client, void *arg)
{
    login(client, (const char *) arg);
}

void login(FILE *client, const char *dbfile)
{
    struct database db;
    struct USER_MESSAGE user_message = {};
    DEBUG_PRINT("login \r\n");
    if (database_open(&db, dbfile) != 0) 
    {
        RESPOND(client, 421, "database error");
        fclose(client);
        return;
    } 
    else 
    {
        RESPOND(client, 220, "localhost");
    }

    char from[512] = {0};

    while (!feof(client)) 
    {
        char line[512];
        fgets(line, sizeof(line), client);
        char command[5] = {line[0], line[1], line[2], line[3]};

        if (strcmp(command, "REGI") == 0) 
        {
            memcpy(user_message.username,line + 4,strstr(line,";") - line - 4);
            strcpy(user_message.password,strstr(line,";") + 1);
            DEBUG_PRINT("%s\r\n",user_message.username);
            DEBUG_PRINT("%s\r\n",user_message.password);

            if(database_send_user_info(&db,user_message.username,user_message.password) < 0)
            {
                DEBUG_PRINT("insert error\r\n");
                RESPOND(client, -1, "ERROR");
            }
            else
            {
                DEBUG_PRINT("insert successful\r\n");
                RESPOND(client, 0, "OK");
            }
        } 
        else if (strcmp(command, "LOGI") == 0) 
        {
            memcpy(user_message.username,line + 4,strstr(line,";") - line - 4);
            strcpy(user_message.password,strstr(line,";") + 1);
            DEBUG_PRINT("%s\r\n",user_message.username);
            DEBUG_PRINT("%s\r\n",user_message.password);

            if(database_list_user_info(&db,user_message.username,user_message.password) == NULL)
            {
                DEBUG_PRINT("login error\r\n");
                RESPOND(client, -1, "ERROR");
            }
            else
            {
                DEBUG_PRINT("login successful\r\n");
                RESPOND(client, 0, "OK");
            }
        }
        else 
        {
            RESPOND(client, 500, "command unrecognized");
        }
        DEBUG_PRINT("round\r\n");
    }
    DEBUG_PRINT("finish\r\n");
    fclose(client);
    database_close(&db);
}
